<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//  获取用户信息- 2016年9月20日 星期二
use think\Config;
use think\Loader;

function getUser($key=null){
    $data = isset($_SESSION['login'])? $_SESSION['login']:array();
    if($key){
        if(array_key_exists($key,$data)) return $data[$key];
        return '';
    }
    return $data;
}
//  输出调试信息 $print == die 时中断程序 -2016年9月20日 星期二
function debugOut($data=null,$print=false){
    $str = '';
    if(is_object($data) || is_array($data)){
        $data = is_object($data)? (array)$data:$data;
        $str = print_r($data,true);
    }elseif(empty($data)) $str = '';
    else $str = $data;
    if($print){
        header('content-type:text/html;charset=utf-8;');
        echo '<h4>('.date('Y-m-d H:i:s').')调试信息：</h4><pre>'.$str.'</pre>';
        if('die' == $print) die;
        return;
    }
    $conf = brximl_conf();
    $dir = ROOT_PATH.'/'.$conf['debug_dir'];
    if(!is_dir($dir)) mkdir($dir);
    $file = $dir.'debug'.date('Y-m-d').'.log';
    $str = "\r\n--------------|| ".date('Y-m-d H:i:s')." ||------------->\r\n".$str;
    if(!is_file($file)) file_put_contents($file,$str);
    else{
        $fh = fopen($file,'a');
        fwrite($fh,$str);
        fclose($fh);
    }
}
//  私有配置文件 brximl_ 打头为私有函数区别于系统方法
function brximl_conf($key=null){
    $name = 'user';
    Config::load(APP_PATH.'conf.php','',$name);
    //  预处理配置解析常量
    Config::set('dir',str_replace('/app/','',APP_PATH),$name);
    return Config::get($key,$name);
}

/*通过解析获取URL左/右邻值*/
function getUrlBind($name=null,$ogri=false,$position='LEFT'){
    //$url = $_SERVER["REQUEST_URI"];
    $url = $_REQUEST["s"];
    $arr = explode('/',$url);
    if(empty($name)) return $arr;
    $key = array_search($name,$arr);
    if(empty($key)) $key = array_search($name.'.html',$arr);
    if(empty($key)) return '';
    $key = $position == 'LEFT'? $key+1:$key-1;
    if(isset($arr[$key])){
        if($ogri) return $arr[$key];
        $tmpArr = explode('.',$arr[$key]);
        return $tmpArr[0]; 
    }
    return '';
}
/* 用户选择器*/
function user_select($opt=null){
    $page = isset($opt['page'])? $opt['page']:1;
    $num = isset($opt['num'])? $opt['num']:20;
    $xhtml = '';
    $user = Loader::model('User');
    $data = $user//->where('user_name,user_code')
            ->field('user_name,user_code')
            ->page($page,$num)
            ->select();
    foreach($data as $v){
        $xhtml .= '<li><a href="javascript:void(0);" code="'.$v['user_code'].'" onclick="TeC.select_user(this);">'.$v['user_name'].'</a></li>';
    }
    if($xhtml){
        $xhtml = '<ul>'.$xhtml.'</ul>';
        $count = $user->count();
        $xhtml .= getPageBar($page,$count,$num,'<<');
    }
    return $xhtml;
}
// 分页器
function getPageBar($page=1,$count,$num=20,$type=null){
    $xhtml = '';
    $all = ceil($count/$num);// 总页数
    if($all == 1) return $xhtml;
    if('<<' == $type){// << < 跳转 > >> 符号分法
        if($page>2) $xhtml .= '<a href="javascript:TeC.pageTo(\'1\')"><<</a>';
        if($page>1) $xhtml .= '<a href="javascript:TeC.pageTo(\''.($page-1).'\')"><</a>';

        if($page<$all) $xhtml .= '<a href="javascript:TeC.pageTo(\''.($page+1).'\')">></a>';
        if($page<$all-1) $xhtml .= '<a href="javascript:TeC.pageTo(\''.$all.'\')">>></a>';
    }else{// 默认十分法 
        $fmod = fmod($page,10);
        $min = $page-$fmod+1;
        $max = $page-$fmod+10;
        if($max>$all) $max = $all;
        if($min>10) $xhtml = '<a href="javascript:TeC.pageTo(\''.($min-1).'\')" class="page_bar_btn"><</a>';
        for($i=$min; $i<=$max; $i++){
            $xhtml .= '<a href="javascript:TeC.pageTo(\''.$i.'\')" class="'.($page == $i? 'page_bar_active':'page_bar_btn').'">'.$i.'</a>';
        }
        if($max<$all) $xhtml = '<a href="javascript:TeC.pageTo(\''.($max+1).'\')" class="page_bar_btn">></a>';
    }
    $xhtml .= '<span class="page_bar_info">'.$page.'/<span class="page_bar_max">'.$all.'</span>,获取到条'.$count.'数据</span>';
    return $xhtml;
}

// 生成跨端口请求地址
function getPortUrl($url,$port=null){
    return 'http://'.request()->ip().(is_numeric($port)? ':'.$port:'').$url;
}

/************** 互联网APIs begin ***********************/
/*
	参考： http://httpbin.org/,http://www.niubb.net/a/2015/05-01/368660.html
*/
function curNet()
{
	//1.获取当前的IP
	$ipArr = json_decode(trim(getStr('http://httpbin.org/ip')),true);
	$url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ipArr['origin'];/*测试curl方式下最稳定*/
	//$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='.$ipArr['origin'];
	//$url = 'http://www.niubb.netsmartresult-xml/search.s?type=ip&q='.$ipArr['origin'];
	//$url = 'http://whois.pconline.com.cn/?ip='.$ipArr['origin'];

	//2.调用淘宝API
	$arr = getStr($url,true);
	if($arr['code'] == 1){//数据获取失败
		$arr = array();
		$iplookup = getStr('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js');//未知IP省获取位置
		$arr['data'] = json_decode(str_replace('var remote_ip_info = ','',rtrim(trim($iplookup),';')),true);//var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u9ed1\u9f99\u6c5f","city":"\u54c8\u5c14\u6ee8","district":"","isp":"","type":"","desc":""};
		$arr['ip'] = $ipArr['origin'];
	}
	$arr['stamp'] = date('Y-m-d H:i:s');//timestamp时间戳
	return $arr;
}
/*函数库
    CURL
*/
function getStr($url,$type=null,$data=null)
{
	if(!extension_loaded('curl')){
		ini_set('curl',true);
	}
	$ch = curl_init();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	if($data){//post 数据
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0');
	}
	//curl_setopt ( $ch, CURLOPT_HEADER, 0 );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

	$res = curl_exec ( $ch );
	if(empty($res)){
		return curl_error($ch);
	}
	curl_close ($ch);
	$resed = @iconv("", "UTF-8", $res);//PHP_EOL;
	if($type) $resed = json_decode($resed,true);
	if(empty($resed)){//数据处理失败时>> 返回初始结果
		return $res;
	}
	return $resed;
}
/*获取网页内容的另外一种方式
*/
function getContent($opt)
{
    $result = '';
    $post = isset($opt['data'])? $opt['data']:null;
    $url = is_string($opt)? $opt:$opt['url'];
    if(empty($url)) return '';
    if($post){// POST-data
        if(!is_array($post)) $post = json_decode(trim($post),true);
        if(is_array($post)){
            $postStr =  http_build_query($post);
            $opts = ['http' =>
                [
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postStr
                ]
            ];
            $context  = stream_context_create($opts);
            $result = file_get_contents($url, false, $context);
        }
    }else{
        $result = file_get_contents($url);
    }
    return $result;
}
/************** 互联网APIs end ***********************/